#include "tpthread.h"
#include "threadpool.h"
#include <thread>

void *
task(void *data, int id)
{
    PThread *t = (PThread *)data;
    while (t->active())
    {
        srand(time(NULL) + id);
        int count = rand() % 500;

        /* printf("thread: %d, msleep: %d\n", id, count); */
        std::this_thread::sleep_for(std::chrono::milliseconds(count));
    }

    return NULL;
}


ThreadPool *tpool = NULL;

const int N = 1000;
int main()
{
    tpool = new ThreadPool();

    /* PThread t1; */
    /* t1.setEntry(task, &t1); */
    /* t1.start(); */

    /* getchar(); */
    /* t1.stop(); */

    /* getchar(); */
#if 1 
    PThread *t[N] = {NULL};
    for (int i = 0; i < N; ++i)
    {
        t[i] = new PThread();
        t[i]->setEntry(task, t[i], i);
        t[i]->start();
    }

    getchar();
    for (int i = 0; i < N; ++i)
    {
        t[i]->stop();

        /* will crash!!!! */
        delete t[i];
    }
#else
    PThread t[N];
    for (int i = 0; i < N; ++i)
    {
        t[i].setEntry(task, &t[i], i);
        t[i].start();
    }

    //getchar();
    for (int i = 0; i < N; ++i)
    {
        t[i].stop();
    }
#endif

    getchar();
    delete tpool;
    tpool = NULL;

    return 0;
}
